//
//  QYDataHelper.swift
//  KunLanCamera
//
//  Created by 李东 on 2024/3/23.
//

import UIKit
import HandyJSON
class QYDataHelper: NSObject {

    static let shared = QYDataHelper()
    let LocalKey = "dataKey"
    lazy var array = [QYDataModel]()
    
    
    func getLocalList(isRefresh: Bool = false) -> [QYDataModel] {
        if !isRefresh && !array.isEmpty {
            return array
        }
        if let tt = UserDefaults.standard.object(forKey: LocalKey) as? String {
            if let list = [QYDataModel].deserialize(from: tt) as? [QYDataModel] {
                array = list.sorted(by: { m1, m2 in
                    m1.ts < m2.ts
                })
            }
        }
        return array
    }
    
    func addData(model: QYDataModel)  {
        if array.contains(where: {$0.ids == model.ids}) {
            if let ii = array.firstIndex(where: {$0.ids == model.ids}) {
                array[ii] = model
            }
        }else {
            array.append(model)
//            array.insert(model, at: 0)
        }
        if let json = array.toJSONString() {
            UserDefaults.standard.set(json, forKey: LocalKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    func delete(model: QYDataModel) {
        array.removeAll(where: {$0.ids == model.ids})
        if let json = array.toJSONString() {
            UserDefaults.standard.set(json, forKey: LocalKey)
            UserDefaults.standard.synchronize()
        }
    }
    

}
